const fs = require('fs-extra');
const path = require('path');
const { LarkClient } = require('./client');

/**
 * 递归获取文件夹中的所有文档
 * @param {LarkClient} client 飞书客户端
 * @param {string} folderToken 文件夹token
 * @param {Array} documents 文档列表
 * @returns {Promise<Array>}
 */
async function getAllDocuments(client, folderToken, documents = []) {
  try {
    const children = await client.getFolderChildren(folderToken);
    
    for (const item of children.children) {
      if (item.type === 'folder') {
        // 递归处理子文件夹
        await getAllDocuments(client, item.token, documents);
      } else if (item.type === 'docx' || item.type === 'doc') {
        // 添加文档到列表
        documents.push({
          title: item.name,
          token: item.token,
          type: item.type
        });
      }
    }
    
    return documents;
  } catch (error) {
    console.error(`获取文件夹 ${folderToken} 中的文档时出错:`, error.message);
    return documents;
  }
}

/**
 * 导出单个文档
 * @param {LarkClient} client 飞书客户端
 * @param {Object} document 文档信息
 * @param {string} outputPath 输出路径
 * @param {string} format 导出格式
 * @returns {Promise<boolean>}
 */
async function exportDocument(client, document, outputPath, format) {
  try {
    console.log(`正在导出文档: ${document.title}`);
    
    // 创建导出任务
    const task = await client.createExportTask(document.token, format);
    
    // 轮询任务状态
    let taskResult;
    const maxRetries = 30;
    let retries = 0;
    
    while (retries < maxRetries) {
      taskResult = await client.getExportTaskResult(task.ticket);
      
      if (taskResult.result.job_status === 'success') {
        break;
      } else if (taskResult.result.job_status === 'failed') {
        throw new Error('导出任务失败');
      }
      
      // 等待5秒后重试
      await new Promise(resolve => setTimeout(resolve, 5000));
      retries++;
    }
    
    if (retries >= maxRetries) {
      throw new Error('导出任务超时');
    }
    
    // 确定文件扩展名
    let extension = '.docx';
    if (format === 'markdown') {
      extension = '.md';
    } else if (format === 'pdf') {
      extension = '.pdf';
    }
    
    // 构造文件路径
    const fileName = `${document.title}${extension}`;
    const filePath = path.join(outputPath, fileName);
    
    // 下载文件
    await client.downloadExportedFile(taskResult.result.file_token, filePath);
    
    console.log(`文档导出成功: ${fileName}`);
    return true;
  } catch (error) {
    console.error(`导出文档 ${document.title} 时出错:`, error.message);
    return false;
  }
}

/**
 * 导出知识库中的所有文档
 * @param {Object} config 配置信息
 * @param {string} outputPath 输出路径
 * @param {string} format 导出格式
 * @returns {Promise<void>}
 */
async function exportDocuments(config, outputPath, format) {
  const client = new LarkClient(config);
  
  try {
    // 获取根目录
    console.log('正在获取根目录信息...');
    const rootFolder = await client.getRootFolder();
    console.log(`根目录: ${rootFolder.name}`);
    
    // 获取所有文档
    console.log('正在获取文档列表...');
    const documents = await getAllDocuments(client, rootFolder.token);
    console.log(`找到 ${documents.length} 个文档`);
    
    // 创建导出目录
    const exportPath = path.join(outputPath, `export_${new Date().getTime()}`);
    await fs.ensureDir(exportPath);
    
    // 导出每个文档
    let successCount = 0;
    for (const document of documents) {
      const success = await exportDocument(client, document, exportPath, format);
      if (success) {
        successCount++;
      }
      
      // 添加延迟以避免请求过于频繁
      await new Promise(resolve => setTimeout(resolve, 1000));
    }
    
    console.log(`导出完成! 成功: ${successCount}/${documents.length}`);
  } catch (error) {
    console.error('导出过程中发生错误:', error.message);
    throw error;
  }
}

module.exports = {
  exportDocuments
};